package com.lzq.chatroom_project.common.utils;

import com.lzq.chatroom_project.common.pojo.ResultCode;
import com.lzq.chatroom_project.common.pojo.Result;

import lombok.extern.slf4j.Slf4j;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtParserBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.io.Decoders;
import io.jsonwebtoken.security.Keys;

import javax.crypto.SecretKey;
import java.util.Date;
import java.util.Map;


@Slf4j
public class JwtUtil {
    //密钥
    public static String secret = "dVnsmy+SIX6pNptQdeclDSJ26EMSPEIhvZYKBTTug4k=";
    //过期时间
    public static long expiration = 12*60*60*1000;
    //生成安全密钥
    private static SecretKey secretKey = Keys.hmacShaKeyFor(Decoders.BASE64.decode(secret));

    /**
     * 获取JWT令牌
     * @param claim 传入信息
     * @return JWT令牌(字符串)
     */
    public static String genJwt(Map<String,Object> claim) {
        String jwt = Jwts.builder()
                .setClaims(claim)
                .setIssuedAt(new Date())
                .setExpiration(new Date(System.currentTimeMillis()+expiration))
                .signWith(secretKey)
                .compact();
        return jwt;
    }

    /**
     * 验证密钥
     * @param jwt JWT令牌
     * @return
     */
    public static Result parseJwt(String jwt) {
        if (!StringUtils.hasLength(jwt)) {
            log.info("传入的jwt令牌为空");
            return Result.failed(ResultCode.FAILED_PARAMS_VALIDATE);
        }
        JwtParserBuilder jwtParserBuilder = Jwts.parserBuilder().setSigningKey(secretKey);
        Claims claims = null;
        try {
            claims = jwtParserBuilder.build().parseClaimsJws(jwt).getBody();
        }catch (Exception e) {
            log.error("解析令牌错误:{}",jwt);
            return Result.failed(ResultCode.FAILED);
        }
        return Result.success(claims);
    }

    public static Result getUserIdFromToken(String jwt) {
        Assert.notNull(jwt,"传入的jwt令牌为空");
        JwtParserBuilder jwtParserBuilder = Jwts.parserBuilder().setSigningKey(secretKey);
        Claims claims = null;
        try {
            claims = jwtParserBuilder.build().parseClaimsJws(jwt).getBody();
        }catch (Exception e) {
            log.error("解析令牌错误:{}",jwt);
            return Result.failed(ResultCode.FAILED);
        }
        Integer userId = (Integer) claims.get("id");
        log.info("查询到用户登录的id:{}",userId);
        return Result.success(userId);
    }
}
